package com.example.demo.controller;

import com.example.demo.common.JsonResult;
import com.example.demo.common.UserSessionUtils;
import com.example.demo.entity.Order;
import com.example.demo.entity.vo.OrderVO;
import com.example.demo.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;

@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private ThreadPoolTaskExecutor workPool;



    // 用户只能查看自己的订单
    @RequestMapping("/getlist")
    public JsonResult getList(HttpServletRequest request, Integer orderId, Integer pSize, Integer pIndex) throws ExecutionException, InterruptedException {
        return JsonResult.success(getOrderMap(UserSessionUtils.getUserId(request), orderId, pSize, pIndex));
    }

    // 管理员查看所有的订单
    @RequestMapping("/admin/getlist")
    public JsonResult adminGetList(Integer orderId, Integer pSize, Integer pIndex) throws ExecutionException, InterruptedException {
        return JsonResult.success(getOrderMap(null, orderId, pSize, pIndex));
    }

    // 实现分页查询订单列表
    private HashMap<String, Object> getOrderMap(Integer userId, Integer orderId, Integer pSize, Integer pIndex) throws ExecutionException, InterruptedException {
        List<OrderVO> list;     // 当前页订单
        Integer pageCount = 0;      // 总页数

        // 1. 校正参数, 参数不合法的情况下
        if (pSize == null || pSize <= 1) {
            pSize = 10;
        }
        if (pIndex == null || pIndex <= 0) {
            pIndex = 1;
        }
        // 2. 计算 offset
        pIndex = (pIndex - 1) * pSize;
        // 3. 获取当前页的订单列表
        Integer finalPSize = pSize;
        Integer finalPIndex = pIndex;
        FutureTask<List<OrderVO>> orderList = new FutureTask<>(() -> orderService.getList(userId, orderId, finalPSize, finalPIndex));
        workPool.submit(orderList);

        // 4. 获取总页数
        if (orderId == null) {
            FutureTask<Integer> pCount = new FutureTask<>(() -> {
                // a. 获取订单总数
                int totalCount = orderService.getCount(userId);
                // b. 总页数 = 订单总数 / pSize    向上取整
                return (int) Math.ceil(totalCount * 1.0 / finalPSize);
            });
            workPool.submit(pCount);
            pageCount = pCount.get();
        }

        // 获取线程执行结果
        list = orderList.get();

        // 5. 组装数据，然后 return
        HashMap<String, Object> map = new HashMap<>();
        map.put("orderList", list);
        map.put("pageCount", pageCount);
        return map;
    }

    // 用户取消订单
    @RequestMapping("/cancel")
    public JsonResult updateState(HttpServletRequest request, Integer orderId) {
        if (orderId == null || orderId <= 0) {
            return JsonResult.failure(-1, "非法参数");
        }
        return JsonResult.success(orderService.update(orderId, UserSessionUtils.getUserId(request), -1));
    }

    // 管理员更新订单状态
    @RequestMapping("/admin/update")
    public JsonResult adminUpdateState(Integer orderId, Integer state) {
        if (orderId == null || state == null) {
            return JsonResult.failure(-1, "非法参数");
        }
        // 管理员更新的订单状态为 0， 1， 2
        if (state != 0 && state != 1 && state != 2) {
            return JsonResult.failure(-1, "非法参数");
        }
        return JsonResult.success(orderService.update(orderId, null, state));
    }

    // 用户下单
    @RequestMapping("/add")
    public JsonResult add(HttpServletRequest request, Order order, @RequestParam(value = "arrDishId", required = false) List<Integer> arrDishId) {
        if (order == null || arrDishId == null || arrDishId.size() == 0) {
            return JsonResult.failure(-1, "非法参数");
        }
        order.setUserId(UserSessionUtils.getUserId(request));
        return JsonResult.success(orderService.add(order, arrDishId));
    }
}
